<?php

/**
 * This is the model class for table "tbl_user".
 *
 * The followings are the available columns in table 'tbl_user':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $firstname
 * @property string $lastname
 * @property string $last_login
 * @property integer $bad_logins
 * @property integer $locked
 * @property string $login_ip
 * @property string $logged_ip
 * @property integer $tbl_access_right_id
 *
 * The followings are the available model relations:
 * @property TblAccessRight $tblAccessRight
 * @property TblUserLog[] $tblUserLogs
 */
class User extends CActiveRecord {

    public $rememberMe;
    private $_identity = NULL;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'tbl_user';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('tbl_access_right_id', 'required' , 'on' => 'insert'),
            array('username', 'required' , 'on' => 'login'),
            array('bad_logins, locked, tbl_access_right_id', 'numerical', 'integerOnly' => true),
            array('username, password', 'length', 'max' => 30),
            array('firstname, lastname', 'length', 'max' => 255),
            array('last_login, login_ip, logged_ip', 'length', 'max' => 16),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, username, password, firstname, lastname, last_login, bad_logins, locked, login_ip, logged_ip, tbl_access_right_id', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'tblAccessRight' => array(self::BELONGS_TO, 'TblAccessRight', 'tbl_access_right_id'),
            'tblUserLogs' => array(self::HAS_MANY, 'TblUserLog', 'tbl_user_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'firstname' => 'Firstname',
            'lastname' => 'Lastname',
            'last_login' => 'Last Login',
            'bad_logins' => 'Bad Logins',
            'locked' => 'Locked',
            'login_ip' => 'Login Ip',
            'logged_ip' => 'Logged Ip',
            'tbl_access_right_id' => 'Tbl Access Right',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('username', $this->username, true);
        $criteria->compare('password', $this->password, true);
        $criteria->compare('firstname', $this->firstname, true);
        $criteria->compare('lastname', $this->lastname, true);
        $criteria->compare('last_login', $this->last_login, true);
        $criteria->compare('bad_logins', $this->bad_logins);
        $criteria->compare('locked', $this->locked);
        $criteria->compare('login_ip', $this->login_ip, true);
        $criteria->compare('logged_ip', $this->logged_ip, true);
//        $criteria->compare('tbl_access_right_id', $this->tbl_access_right_id);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    /**
     * Logs in the user using the given username and password in the model.
     * @return boolean whether login is successful
     */
    public function login() {
        if ($this->_identity === null) {
            $this->_identity = new UserIdentity($this->username, $this->password);
            if (!$this->_identity->authenticate()) {          // login errors
                switch ($this->_identity->errorCode) {
                    case UserIdentity::ERROR_NO_ACCESS:
                        $this->addError('username', 'You are locked.');
                        break;
                    case UserIdentity::ERROR_BAD_LOGINS:
                        $this->addError('username', 'Too many bad logins.');
                        break;
                    case UserIdentity::ERROR_BAD_IP:
                        $this->addError('username', 'You are coming from disallowed ip.');
                        break;
                    case UserIdentity::ERROR_USERNAME_INVALID:
                    case UserIdentity::ERROR_PASSWORD_INVALID:
                        $this->addError('username', 'Incorrect username or password.');
                        break;
                    default:
                }
            }
        }
        if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {        // logged in
            $duration = $this->rememberMe ? 3600 * 24 * 30 : 0;                // 30 days
            Yii::app()->user->login($this->_identity, $duration);
            return true;
        }
        else
            return false;
    }

}